package com.yjzx.util.common.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author yjzx
 * @create 2023-03-08
 * @Description HttpClient类 get，post请求
 */
public class HttpClientUtil {
    /*
            <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
     */
    /**
     * 线程池管理
     */
    private final static PoolingHttpClientConnectionManager poolConnManager ;
    private final static CloseableHttpClient client  ;

    /*
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </dependency>
     */
    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, (chain, authType)->chain.length>=1);
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();
            // 初始化连接管理器
            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            poolConnManager.setMaxTotal(64);
            // 设置最大路由
            poolConnManager.setDefaultMaxPerRoute(32);
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(30000)
                    .setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            client = HttpClients.custom()
                    // 设置连接池管理
                    .setConnectionManager(poolConnManager)
                    .setDefaultRequestConfig(config)
                    // 设置重试次数
                    .setRetryHandler(
                            new DefaultHttpRequestRetryHandler(2, false))
                    .build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private static CloseableHttpClient getDefaultConnection() {
        return HttpClients.createDefault();
    }


    /**
     * 获取连接池连接
     *
     * @return
     */
    private static CloseableHttpClient getConnection() {
        return client;
    }

    public static String doDefaultGet(String url) {
        return doGet(url, getDefaultConnection());
    }

    public static String doGet(String url) {
        return doGet(url, getConnection());
    }

    public static String doGet(String url, CloseableHttpClient httpClient) {
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void doDefaultDownload(String url, String fileName) {
        download(url, fileName, getDefaultConnection());
    }

    public static void download(String url, String fileName) {
        download(url, fileName, getConnection());
    }

    public static void download(String url, String fileName, CloseableHttpClient httpClient) {
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();

                // String result = EntityUtils.toString(entity, "UTF-8");
                byte[] bytes = EntityUtils.toByteArray(entity);
                File file = new File(fileName);
                //  InputStream in = entity.getContent();
                FileOutputStream fout = new FileOutputStream(file);
                fout.write(bytes);
                EntityUtils.consume(entity);
                fout.flush();
                fout.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return;
    }

    public static String doDefaultPost(String url, Map paramBody, Header... heads) {
        return doPost(url, paramBody, getDefaultConnection(), heads);
    }

    public static String doPost(String url, Map paramBody, Header... heads) {
        return doPost(url, paramBody, getConnection(), heads);
    }

    public static String doPost(String url, Map paramBody, CloseableHttpClient httpClient, Header... heads) {
        String paramBodyStr = null;
        try {
            paramBodyStr = new ObjectMapper().writeValueAsString(paramBody);
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpResponse response = null;
            try {
                StringEntity entity = new StringEntity(paramBodyStr);
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                if (heads != null) {
                    httpPost.setHeaders(heads);
                }
                response = httpClient.execute(httpPost);
                int code = response.getStatusLine().getStatusCode();
                String result = EntityUtils.toString(response.getEntity());
                if (code == HttpStatus.SC_OK) {
                    return result;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (
                JsonProcessingException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("=====>发起请求出现异常！");
    }




}
